package hash;

import java.util.HashSet;
import java.util.Set;

/**
 * https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/
 * 最长无重复子字符串
 */
public class LongestSubString {


    public static void main(String[] args) {

        String s = "abcabcbb";
        System.out.println(new LongestSubString().lengthOfLongestSubstring(s) );
        System.out.println("array impl :");
        System.out.println(new LongestSubString().lengthOfLongestSubstringArray(s) );
    }

    public int lengthOfLongestSubstring(String s) {
        // write your code here
        Set<Character> set = new HashSet<>();
        if (s == null || s.length() == 0) {
            return 0;
        }
        int max = 0;
        int right = 0;
        for (int i = 0; i < s.length(); i++) {
            while (right < s.length() && !set.contains(s.charAt(right))) {
                set.add(s.charAt(right++));
                max = Math.max(max, right - i);
            }
            set.remove(s.charAt(i));
        }
        return max;
    }

    public int lengthOfLongestSubstringArray(String s) {
        // write your code here
        if (s == null || s.length() == 0) {
            return 0;
        }

        int i = 0;
        int j = 0;
        int ans = 0;
        int[] map = new int[256];
        for (i = 0; i < s.length(); i++) {
            while (j < s.length() && map[s.charAt(j)] == 0) {
                map[s.charAt(j)] = 1;
                ans = Math.max(ans, j - i + 1);
                j++;
            }
            map[s.charAt(i)] = 0;
        }
        return ans;
    }
}
